package cn.lau.demo.service.impl;

import cn.lau.demo.auth.JWTToken;
import cn.lau.demo.pojo.User;
import cn.lau.demo.service.UserService;
import cn.lau.demo.util.JWTUtil;
import com.sun.istack.internal.NotNull;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("userService")
public class UserServiceImpl implements UserService {

	/* 模拟数据源 */
	private static volatile HashMap<String, User> datasource = new HashMap<>();

	static {
		HashSet<String> adminRoleSet = new HashSet<>();
		adminRoleSet.add("ADMIN");
		adminRoleSet.add("USER");
		HashSet<String> userRoleSet = new HashSet<>();
		userRoleSet.add("USER");

		List<String> adminPermList = new ArrayList<>();
		adminPermList.add("prod:add");
		adminPermList.add("prod:update");
		adminPermList.add("prod:get");
		adminPermList.add("prod:delete");
		List<String> userPermList = new ArrayList<>();
		userPermList.add("prod:get");

		/*
		* 用户名：admin, 密码：2a829385f556570c0574e86111473da8, 盐值：8f3644c2ea69415ebad8c471a3b27275
		* 用户名：user, 密码：403f6d39e9301deac93605d41a32237b, 盐值：5105581deb01467cb0a68f1f5c803b38
		* 用户名：devil, 密码：929e800e43beb781081e983de757b858, 盐值：935926eee71d4155b1dc8acc56f42524
		* */
		User admin = new User(1, "admin", "2a829385f556570c0574e86111473da8", "8f3644c2ea69415ebad8c471a3b27275", adminPermList, adminRoleSet, false);
		User user = new User(2, "user", "403f6d39e9301deac93605d41a32237b", "5105581deb01467cb0a68f1f5c803b38", userPermList, userRoleSet, false);
		User lockedUser = new User(3, "devil", "929e800e43beb781081e983de757b858", "935926eee71d4155b1dc8acc56f42524", Collections.EMPTY_LIST, Collections.EMPTY_SET, true);
		datasource.put("admin", admin);
		datasource.put("user", user);
		datasource.put("devil", lockedUser);
		System.out.println("[用户名]-[密码] [admin]-[admin] [user]-[123] [devil]-[evil]");
	}

	private final static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

	@Override
	public Map<String, Object> login(@NotNull String username, @NotNull String password) {
		Map<String, Object> result = new HashMap<>();
		String token;

		JWTToken jwtToken = new JWTToken(username, password);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(jwtToken);
		} catch (IncorrectCredentialsException | UnknownAccountException e) {
			LOGGER.info("登录异常，错误信息：{}", e.getMessage());
			result.put("code", 1);
			result.put("msg", "用户名或者密码错误");
			result.put("data", null);
			return result;
		} catch (AuthenticationException ae) {
			LOGGER.info("登录异常，错误信息：{}", ae.getMessage());
			result.put("code", 1);
			result.put("msg", ae.getMessage());
			result.put("data", null);
			return result;
		}
		LOGGER.info("用户登录成功：{}", username);
		result.put("code", 0);
		result.put("msg", "success");
		// 登录成功签发token
		token = JWTUtil.sign((User) currentUser.getPrincipal());    // todo 为什么SecurityUtils.getSubject().getPrincipal()获取到的是User对象
		result.put("data", token);
		return result;
	}

	@Override
	public User getByUsername(String username) {
		if (!datasource.containsKey(username)) return null;
		return datasource.get(username);
	}
}
